package com.admin.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.admin.dao.AdminCTSDao;
import com.admin.dao.AdminChooseDao;
import com.admin.dao.AdminProjectDao;
import com.admin.model.AutoChooseSucceedResult;
import com.admin.model.ExcelReadResult;
import com.admin.model.FileMeta;
import com.admin.model.ImportExcelReprotModel;
import com.admin.model.StudentWithChooseInfo;
import com.admin.util.AdminProjectExcelTool;
import com.admin.util.AdminScoreExcelTool;
import com.common.model.AdminUser;
import com.common.model.ProfBranch;
import com.common.model.Project;
import com.common.model.Score;
import com.common.model.StudentUser;
import com.common.model.TeacherUser;
import com.common.model.TimePlan;
import com.teacher.model.ProjAndProf;

@Service
public class AdminChooseService {
	@Autowired
	@Qualifier("adminChooseDao")
	AdminChooseDao dao;
	@Autowired
	@Qualifier("adminProjcectDao")
	AdminProjectDao prjDao;
	@Autowired
	@Qualifier("adminCTSDao")
	AdminCTSDao ctsDao;
	/**
	 * 获取某班级下没有选毕业设计的学生名单
	 * @param classId
	 * @param page
	 * @return
	 */
	public ArrayList<StudentWithChooseInfo> getUnchooseListByClassId(int classId,int page){
		if(page<1){
			page=1;
		}
		int start=(page-1)*10;
		return dao.getUnchooseListByClassId(classId, start);
	}
	/**
	 * 获取某班级下没有选毕业设计的学生人数
	 * @param classId
	 * @return
	 */
	public int getUnchooseCountByClassId(int classId){
		return dao.getUnchooseCountByClassId(classId);
	}
	/**
	 * 查找某个学生可选的题目列表
	 * @param stuId
	 * @return
	 */
	public ArrayList<Project> getAvailableProjectOfStudent(int stuId){
		return dao.getAvailableProjectOfStudent(stuId);
	}
	/**
	 * 手动选题
	 * @param prjId
	 * @param stuId
	 * @return -1无题目 -2 无学生 -3 题目已选 -4 未审核 -5专业方向不适合 -6已选题目 -7其他错误
	 */
	public int setChooseManual(int prjId,int stuId){
		Project prj=prjDao.getProjectByPrjId(prjId);
		if(prj==null){
			return -1;
		}
		StudentUser stu=ctsDao.getStudentByStuId(stuId);
		if(stu==null){
			return -2;
		}
		if(prj.getStu_id()!=null){
			return -3;
		}
		if(!prj.getStatus().equals(Project.PASSED)){
			return -4;
		}
		List<ProjAndProf> papList=prj.getProfs();
		int stuBranch=stu.getClassInfo().getBranch().getId();
		boolean branchMatch=false;
		for (ProjAndProf pap : papList) {
			if(pap.getBranch().getId()==stuBranch){
				branchMatch=true;
				break;
			}
		}
		if(!branchMatch){
			return -5;
		}
		if(dao.getPrjCountByStuId(stuId)>0){
			return -6;
		}
		try {
			dao.setChooseManual(prjId, stuId);
			//dao.deleteIntentChooseOfStu(stuId);
		} catch (Exception e) {
			return -7;
		}
		return 0;
	}
	/**
	 * 查询所有未选题的学生名单
	 * @return
	 */
	public ArrayList<StudentUser>getUnchooseListByAll(){
		return dao.getUnchooseListByAll();
	}
	public HashMap<String, Object> autoChooseProject(AdminUser admin){
		HashMap<String, Object> result=new HashMap<>();
		ArrayList<AutoChooseSucceedResult> resultList=new ArrayList<>();
		ArrayList<StudentUser>unchooseList=null;
		if(admin.isSuperAdmin()){
			unchooseList=dao.getUnchooseListByAll();
		}else{
			unchooseList=dao.getUnchooseListByCollege(admin.getCollegeId());
		}
		result.put("totalStuCount", unchooseList.size());
		for (StudentUser stu : unchooseList) {
			ArrayList<Project>prjList=dao.getAvailableProjectOfStudent(stu.getId());
			if(prjList!=null&&prjList.size()>0){
				dao.setChooseManual(prjList.get(0).getId(), stu.getId());
				//dao.deleteIntentChooseOfStu( stu.getId());
				AutoChooseSucceedResult r=new AutoChooseSucceedResult();
				r.setPrj(prjList.get(0));
				r.setStu(stu);
				resultList.add(r);
			}
		}
		result.put("successList",resultList);
		result.put("successCount", resultList.size());
		return result;
	}
	/**
	 * 判断是否模式为按题目选
	 * @param clgId
	 * @return
	 */
	public boolean getIsChooseByPrj(int clgId){
		return dao.getIsChooseByPrj(clgId);
	}
	/**
	 * 获取选了某个教师的学生(按教师选) 
	 * @param teaId
	 * @return
	 */
	public ArrayList<StudentUser> getStuListOfChooseTea(int teaId){
		return dao.getStuListOfChooseTea(teaId);
	}
	/**
	 * 获取题目还未选择完毕的教师 (按教师选) 
	 * @param clgId
	 * @return
	 */
	public  ArrayList<HashMap<String,Object>> getUnFinishTeacher(int clgId,int page){
		if (page < 1) {
			page = 1;
		}
		int start = (page - 1) * 10;
		ArrayList<TeacherUser> teaList = dao.getUnFinishTeacher(clgId, start);
		ArrayList<HashMap<String, Object>> result = new ArrayList<>();
		for (TeacherUser tea : teaList) {
			HashMap<String, Object> teaPrjStu = new HashMap<>();
			teaPrjStu.put("tea", tea);
			teaPrjStu.put("stuList", dao.getStuListOfChooseTea(tea.getId()));
			teaPrjStu.put("prjList", dao.getAviablePrjOfTea(tea.getId()));
			result.add(teaPrjStu);
		}
		return result;
	}
	/**
	 * 获取题目还未选择完毕的教师数目(按教师选) 
	 * @param clgId
	 * @return
	 */
	public int getUnFinishTeacherCount(int clgId){
		 return dao.getUnFinishTeacherCount(clgId);
	 }
	/**
	 * 获取某个教师下还可以使用的题目(按教师选) 
	 * @param teaId
	 * @return
	 */
	public ArrayList<Project> getAviablePrjOfTea(int teaId){
		return dao.getAviablePrjOfTea(teaId);
	}
	/**
	 * 获取选取了某个题目的学生(按题目选) 
	 * @param prjId
	 * @return
	 */
	public ArrayList<StudentUser> getStuListOfChoosePrj(int prjId){
		return dao.getStuListOfChoosePrj(prjId);
	}
	/**
	 * 获取还没有学生选择的题目(按题目选) 
	 * @param clgId
	 * @return
	 */
	public ArrayList<HashMap<String,Object>> getUnchooseProject(int clgId,int page){
		
		if(page<1){
			page=1;
		}
		int start=(page-1)*10;
		 ArrayList<Project> prjList=dao.getUnchooseProject(clgId,start);
		 ArrayList<HashMap<String,Object>> result=new ArrayList<>();
		 for (Project prj : prjList) {
			 HashMap<String,Object>prjAndStu=new HashMap<>();
			 prjAndStu.put("prj", prj);
			 prjAndStu.put("stuList", dao.getStuListOfChoosePrj(prj.getId()));
			 result.add(prjAndStu);
		}
		 return result;
	}
	/**
	 * 获取还没有学生选择的题目数目(按题目选)
	 * @param clgId
	 * @return
	 */
	public int getUnchooseProjectCount(int clgId){
		return dao.getUnchooseProjectCount(clgId);
	}
	/**
	 * 查询某学院的设置 
	 * @param clgId
	 * @return
	 */
	public TimePlan getChooseSetOfCollege(int clgId){
		return dao.getChooseSetOfCollege(clgId);
	}
	/**
	 * 修改某学院的选题设置
	 * @param plan
	 * @return
	 */
	public int updateTimeplan(TimePlan plan){
		if(dao.getChooseSetOfCollege(plan.getCollegeId())==null){
			return dao.insertTimePlan(plan);
		}else{
			return dao.updateTimeplan(plan);
		}
	}
	/**
	 * 查询指定学院下所有的成绩
	 * @param clgId
	 * @param start
	 * @return
	 */
	public ArrayList<Score>getScoreByCollege(int clgId,int page){
		if(page<1){
			page=1;
		}
		int start=(page-1)*10;
		return dao.getScoreByCollege(clgId, start);
	}
	/**
	 * 查询指定学院下所有的成绩数量
	 * @param clgId
	 * @return
	 */
	public int getScoreCountByCollege(int clgId){
		return dao.getScoreCountByCollege(clgId);
	}
	public int insertScoreByExcel(FileMeta excel,HttpSession session){
		AdminScoreExcelTool scoreExciseTool=new AdminScoreExcelTool();
		ExcelReadResult<ImportExcelReprotModel<Score>> result= scoreExciseTool.readExcel(excel);
		ExcelReadResult<ImportExcelReprotModel<Score>> error= new ExcelReadResult<>();
		error.setErrorMsg(result.getErrorMsg());
		error.setTotalDataCount(result.getTotalDataCount());
		AdminUser admin=(AdminUser) session.getAttribute("user");
		//致命错误,不导入数据库
		if(result.getErrorMsg()!=null){
			session.setAttribute("scoreExcelReadResult", error);
			session.setAttribute("scoreExcelReadSuccessCount", 0);
			return 0;
		}
		ArrayList<ImportExcelReprotModel<Score>> dataList=result.getDataList();
		int dataSize=dataList.size();
		int successCount=0;
		//循环导入数据库
		for(int i=0;i<dataSize;i++){
			ImportExcelReprotModel<Score> report=dataList.get(i);
			if(report.errorMsg!=null){
				error.getDataList().add(report);
				report.setErrorLine(i+2);
				continue;//此项数据有错,则这一项就不导入数据库
			}
			Score score=report.getData();
			//检查题目信息
			ArrayList<Project>prjArr=prjDao.getProjectsByPrjName(score.getProject().getName());
			//存在性检查
			if(prjArr==null){//不存在1
				report.setErrorMsg("不存在标题为: "+score.getProject().getName()+" 的题目,请重试");
				report.setErrorLine(i+2);
				error.getDataList().add(report);
				continue;
			}
			if(!admin.isSuperAdmin()){
				for (Project prj : prjArr) {
					int prjClgId=prj.getTeacher().getDepartment().getCollege().getId();
					if(admin.getCollegeId()!=prjClgId){
						prjArr.remove(prj);
					}
				}
			}
			if(prjArr.size()>1){
				report.setErrorMsg("存在多个标题为: "+score.getProject().getName()+" 的题目,不能导入");
				report.setErrorLine(i+2);
				error.getDataList().add(report);
				continue;
			}
			if(prjArr.size()==0){
				report.setErrorMsg("不存在标题为: "+score.getProject().getName()+" 的题目,或者题目不属于您的学院");
				report.setErrorLine(i+2);
				error.getDataList().add(report);
				continue;
			}
			Project prj=prjArr.get(0);
			if(!prj.getStatus().equals(Project.PASSED)){
				report.setErrorMsg("题目: "+score.getProject().getName()+" 尚未审核通过,不能导入");
				report.setErrorLine(i+2);
				error.getDataList().add(report);
				continue;
			}
			if(dao.getScoreByPrjId(prj.getId())!=null){
				report.setErrorMsg("题目: "+score.getProject().getName()+" 已经登记过分数");
				report.setErrorLine(i+2);
				error.getDataList().add(report);
				continue;
			}
			score.setProj_id(prj.getId());
			try{
				dao.insertScore(score);
			}catch(Exception e){
				e.printStackTrace();
				report.setErrorMsg("参数错误,请检查");
				report.setErrorLine(i+2);
				error.getDataList().add(report);
				continue;
			}
			successCount++;
		}
		session.setAttribute("scoreExcelReadResult", error);
		session.setAttribute("scoreExcelReadSuccessCount", successCount);
		return 0;
	}
	/**
	 * 查询指定学院下所有的成绩(不分页)
	 * @param clgId
	 * @return
	 */
	public ArrayList<Score>getScoreByCollegeNoPage(int clgId){
		return dao.getScoreByCollegeNoPage(clgId);
	}
}
